﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web;
using mojoPortal.Web.Controls;
using mojoPortal.Web.UI;
using mojoPortal.Web.Framework;
using Resources;

namespace ud_SignIn
{
    public partial class LoginControl : UserControl
    {

        //Constituent controls inside LoginControl
        private SiteLabel lblUserID;
        private SiteLabel lblEmail;
        private TextBox txtUserName;
        private CheckBox chkRememberMe;
        private mojoButton btnLogin;
        private HyperLink lnkRecovery;
        private HyperLink lnkExtraLink;
        private Panel divCaptcha;
        private CaptchaControl captcha;

        private SiteSettings siteSettings;
        private string siteRoot = string.Empty;

        private bool setFocus;
        public bool SetFocus
        {
            get { return setFocus; }
            set { setFocus = value; }
        }

        private bool setRedirectUrl = true;

        public bool SetRedirectUrl
        {
            get { return setRedirectUrl; }
            set { setRedirectUrl = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (Request.IsAuthenticated)
            {
                // user is logged in
                Visible = false;
                return;
            }

            LoadSettings();
            PopulateLabels();

            PopulateControls();

        }

        private void PopulateControls()
        {
            if (siteSettings == null) { return; }
            if (siteSettings.DisableDbAuth) { Visible = false; return; }

            LoginCtrl.SetRedirectUrl = setRedirectUrl;

            lblUserID = (SiteLabel)LoginCtrl.FindControl("lblUserID");
            lblEmail = (SiteLabel)LoginCtrl.FindControl("lblEmail");
            txtUserName = (TextBox)LoginCtrl.FindControl("UserName");
            chkRememberMe = (CheckBox)LoginCtrl.FindControl("RememberMe");
            btnLogin = (mojoButton)LoginCtrl.FindControl("Login");
            lnkRecovery = (HyperLink)LoginCtrl.FindControl("lnkPasswordRecovery");
            lnkExtraLink = (HyperLink)LoginCtrl.FindControl("lnkRegisterExtraLink");

            divCaptcha = (Panel)LoginCtrl.FindControl("divCaptcha");
            captcha = (CaptchaControl)LoginCtrl.FindControl("captcha");
            if (!siteSettings.RequireCaptchaOnLogin)
            {
                if (divCaptcha != null) { divCaptcha.Visible = false; }
                if (captcha != null) { captcha.Captcha.Enabled = false; }
            }
            else
            {
                captcha.ProviderName = siteSettings.CaptchaProvider;
                captcha.RecaptchaPrivateKey = siteSettings.RecaptchaPrivateKey;
                captcha.RecaptchaPublicKey = siteSettings.RecaptchaPublicKey;

            }

            if ((siteSettings.UseEmailForLogin) && (!siteSettings.UseLdapAuth))
            {
                if (!WebConfigSettings.AllowLoginWithUsernameWhenSiteSettingIsUseEmailForLogin)
                {
                    RegularExpressionValidator regexEmail = new RegularExpressionValidator
                                                                {
                                                                    ControlToValidate = txtUserName.ID,
                                                                    ValidationExpression =
                                                                        SecurityHelper.RegexEmailValidationPattern,
                                                                    ErrorMessage =
                                                                        SignInResource.LoginFailedInvalidEmailFormatMessage
                                                                };
                    //regexEmail.ValidationExpression = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$";
                    LoginCtrl.Controls.Add(regexEmail);
                }

            }

            if (siteSettings.UseEmailForLogin && !siteSettings.UseLdapAuth)
            {
                lblUserID.Visible = false;
            }
            else
            {
                lblEmail.Visible = false;
            }

            if (setFocus) { txtUserName.Focus(); }

            lnkRecovery.Visible = (siteSettings.AllowPasswordRetrieval && (!siteSettings.UseLdapAuth ||
                                                                           (siteSettings.UseLdapAuth && WebConfigSettings.UseLDAPFallbackAuthentication)));

            lnkRecovery.NavigateUrl = LoginCtrl.PasswordRecoveryUrl;
            lnkRecovery.Text = LoginCtrl.PasswordRecoveryText;

            lnkExtraLink.NavigateUrl = siteRoot + "/Secure/Register.aspx";
            lnkExtraLink.Text = SignInResource.RegisterLink;
            lnkExtraLink.Visible = siteSettings.AllowNewRegistration;

            string returnUrlParam = Page.Request.Params.Get("returnurl");
            if (!String.IsNullOrEmpty(returnUrlParam))
            {
                //string redirectUrl = returnUrlParam;
                lnkExtraLink.NavigateUrl += "?returnurl=" + returnUrlParam;
            }

            chkRememberMe.Visible = WebConfigSettings.AllowPersistentLoginCookie;
            chkRememberMe.Text = LoginCtrl.RememberMeText;

            btnLogin.Text = LoginCtrl.LoginButtonText;
            SiteUtils.SetButtonAccessKey(btnLogin, SignInResource.LoginAccessKey);
        }

        private void PopulateLabels()
        {

        }

        private void LoadSettings()
        {
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            siteRoot = SiteUtils.GetNavigationSiteRoot();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
        }
    }
}